package com.lincoln.api;

import com.lincoln.bean.ApiCode;
import com.lincoln.entity.todo.DbTodo;
import com.lincoln.entity.todo.TodoStatusEnum;
import com.lincoln.service.TodoService;
import com.lincoln.service.UserService;
import com.lincoln.utils.TimerMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@CrossOrigin
@RestController
@RequestMapping("/todo")
public class TodoController {
    @Autowired
    UserService userService;
    @Autowired
    TodoService todoService;

    @GetMapping("/{id}")
    public ApiCode todo(@PathVariable Long id) throws Exception {
        DbTodo todo = todoService.findById(id);
        if (todo == null) {
            throw new Exception("活动不存在!");
        }
        return ApiCode.build(ApiCode.SUCCESS, todo);
    }

    @PostMapping("/{id}")
    public ApiCode editTodo(@PathVariable Long id, String startTime, String endTime, String title, String descriptor, String hint, Integer number) throws Exception {
        DbTodo todo = todoService.findById(id);
        if (todo == null) {
            throw new Exception("活动不存在!");
        }
        if (StringUtils.isNotEmpty(startTime)) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            todo.setStartTime(simpleDateFormat.parse(startTime));
        }
        if (StringUtils.isNotEmpty(endTime)) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            todo.setEndTime(simpleDateFormat.parse(endTime));
        }
        if (todo.getEndTime() == null || todo.getEndTime().getTime() <= todo.getStartTime().getTime()) {
            todo.setEndTime(new Date(todo.getStartTime().getTime() + 1 * 60 * 60 * 1000));
        }
        if (todo.getStartTime().getTime() <= System.currentTimeMillis()) {
            if (todo.getEndTime().getTime() >= System.currentTimeMillis()) {
                todo.setStatus(TodoStatusEnum.END);
            } else {
                todo.setStatus(TodoStatusEnum.BEGIN);
            }
        } else {
            todo.setStatus(TodoStatusEnum.WATI);
        }

        if (StringUtils.isNotEmpty(title)) {
            todo.setTitle(title);
        }
        if (StringUtils.isNotEmpty(descriptor)) {
            todo.setDescriptor(descriptor);
        }
        if (StringUtils.isNotEmpty(hint)) {
            todo.setHint(hint);
        }
        if (number != null && number >= 0) {
            todo.setNumber(number);
        }
        todoService.save(todo);
        if(todo.getStatus() == TodoStatusEnum.END){
            TimerMap.removeTimer(todo);
        }else {
            TimerMap.removeTimer(todo);
            TimerMap.addTimer(todo);
        }
        return ApiCode.findCode(ApiCode.SUCCESS);
    }
}
